/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.user.web.student;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.sys.web.UserController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.user.entity.student.TpPStudent;
import com.thinkgem.jeesite.modules.user.service.student.TpPStudentService;

import java.util.List;

/**
 * 学生模块Controller
 * @author 康力
 * @version 2018-03-08
 */
@Controller
@RequestMapping(value = "${adminPath}/user/student/tpPStudent")
public class TpPStudentController extends BaseController {
	@Autowired
	private TpPStudentService tpPStudentService;
	@Autowired
	private SystemService systemService;
	
	@ModelAttribute
	public TpPStudent get(@RequestParam(required=false) String id) {
		TpPStudent entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tpPStudentService.get(id);
			entity.setUser(systemService.getUser(id));
		}
		if (entity == null){
			entity = new TpPStudent();
		}
		return entity;
	}
	
	@RequiresPermissions("user:student:tpPStudent:view")
	@RequestMapping(value = {"list", ""})
	public String list(TpPStudent tpPStudent, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<TpPStudent> page = tpPStudentService.findPage(new Page<TpPStudent>(request, response), tpPStudent); 
		model.addAttribute("page", page);
		return "modules/user/student/tpPStudentList";
	}
	@RequiresPermissions("user:student:tpPStudent:view")
	@RequestMapping(value = "userform")
	public String userform(TpPStudent tpPStudent, Model model) {
		User user=tpPStudent.getUser()==null?new User():tpPStudent.getUser();
		if (user.getCompany()==null || user.getCompany().getId()==null){
			user.setCompany(UserUtils.getUser().getCompany());
		}
		if (user.getOffice()==null || user.getOffice().getId()==null){
			user.setOffice(UserUtils.getUser().getOffice());
		}
		model.addAttribute("user", user);
		model.addAttribute("student", tpPStudent);
		model.addAttribute("allRoles", systemService.findAllRole());
		model.addAttribute("returnUrl", "/user/student/tpPStudent/list"+("1".equals(tpPStudent.getIsMaster())?"?isMaster=1":""));
		model.addAttribute("formUrl","/user/student/tpPStudent/userSave");
		return "modules/sys/userForm";
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "userSave")
	public String save(TpPStudent tpPStudent,User user, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		// 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
		if(user!=null) {
			user.setCompany(new Office(request.getParameter("company.id")));
			user.setOffice(new Office(request.getParameter("office.id")));
			// 如果新密码为空，则不更换密码
			if (StringUtils.isNotBlank(user.getNewPassword())) {
				user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
			}else{
				user.setPassword(tpPStudent.getUser().getPassword());
			}
			if (!beanValidator(model, user)) {
				tpPStudent.setUser(user);
				return userform(tpPStudent, model);
			}
			// 角色数据有效性验证，过滤不在授权内的角色
			List<Role> roleList = Lists.newArrayList();
			List<String> roleIdList = user.getRoleIdList();
			for (Role r : systemService.findAllRole()) {
				if (roleIdList.contains(r.getId())) {
					roleList.add(r);
				}
			}
			user.setRoleList(roleList);
			// 保存用户信息
			systemService.saveUser(user);
			// 清除当前用户缓存
			if (user.getLoginName().equals(UserUtils.getUser().getLoginName())) {
				UserUtils.clearCache();
				//UserUtils.getCacheMap().clear();
			}
			addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'成功");
			tpPStudent.setUser(user);
		}
		model.addAttribute("tpPStudent", tpPStudent);
		model.addAttribute("isMaster", tpPStudent.getIsMaster());
		return	"modules/user/student/tpPStudentForm";
	}


	@RequiresPermissions("user:student:tpPStudent:edit")
	@RequestMapping(value = "save")
	public String save(TpPStudent tpPStudent, Model model,HttpServletRequest request, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, tpPStudent)){
			return save(tpPStudent,null, request,model,redirectAttributes);
		}
		tpPStudentService.save(tpPStudent);
		addMessage(redirectAttributes, "保存学生成功");
		return "redirect:"+Global.getAdminPath()+"/user/student/tpPStudent/?repage";
	}
	
	@RequiresPermissions("user:student:tpPStudent:edit")
	@RequestMapping(value = "delete")
	public String delete(TpPStudent tpPStudent, RedirectAttributes redirectAttributes) {
		tpPStudentService.delete(tpPStudent);
		addMessage(redirectAttributes, "删除学生成功");
		return "redirect:"+Global.getAdminPath()+"/user/student/tpPStudent/?repage";
	}

	/**
	 * 下载导入用户数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("user:student:tpPStudent:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "学生数据导入模板.xlsx";
			List<TpPStudent> list = Lists.newArrayList();
			TpPStudent stu=new TpPStudent();
			stu.setStuType("1");
			stu.setUser(UserUtils.getUser());
			list.add(stu);
			new ExportExcel("学员数据", TpPStudent.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/user/student/tpPStudent/?repage";
	}

	/**
	 * 导入用户数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("user:student:tpPStudent:edit")
	@RequestMapping(value = "import", method= RequestMethod.POST)
	public String importFile(MultipartFile file,String isMaster, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/user/student/tpPStudent/?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<TpPStudent> list = ei.getDataList(TpPStudent.class);
			systemService.setFieldId(list);
			for (TpPStudent stu : list){
				try{
					stu.setIsMaster(isMaster);
					redirectAttributes.addFlashAttribute("isMaster", isMaster);
					if ("true".equals(systemService.checkLoginName("", stu.getUser().getLoginName()))){
						User user=stu.getUser();
						user.setId(null);
						user.setPassword(SystemService.entryptPassword("123456"));
						//用户所属部门
						if(user.getOffice() == null ||StringUtils.isEmpty(user.getOffice().getId())){
							user.setOffice(stu.getDepartment());
						}
						BeanValidators.validateWithException(validator, stu.getUser());
						tpPStudentService.save(stu);
						successNum++;
					}else{
						User user=systemService.getUserByLoginName(stu.getUser().getLoginName());
						String userId=user.getId();
						stu.setId(userId);
						user=stu.getUser();user.setId(userId);
						if(user.getOffice() == null ||StringUtils.isEmpty(user.getOffice().getId())){
							user.setOffice(stu.getDepartment());
						}
						BeanValidators.validateWithException(validator, stu.getUser());
						tpPStudentService.save(stu);
						failureMsg.append("<br/>登录名 "+stu.getUser().getLoginName()+" 已存在，更新用户信息");
						failureNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>登录名 "+stu.getUser().getLoginName()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					ex.printStackTrace();
					failureMsg.append("<br/>登录名 "+stu.getUser().getLoginName()+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，覆盖"+failureNum+" 条用户，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条用户"+failureMsg);
		} catch (Exception e) {
			e.printStackTrace();
			addMessage(redirectAttributes, "导入用户失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/user/student/tpPStudent/?repage=&isMaster="+isMaster;
	}
	/**
	 * 导出用户数据
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("user:student:tpPStudent:view")
	@RequestMapping(value = "export", method=RequestMethod.POST)
	public String exportFile(TpPStudent tpPStudent, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "学生用户数据"+ DateUtils.getDate("yyyy-MM-dd")+".xlsx";
//			Page<TpPStudent> page = tpPStudentService.findPage(new Page<TpPStudent>(request, response, -1), tpPStudent);
			new ExportExcel("学生用户数据", TpPStudent.class).setDataList(tpPStudentService.findList(tpPStudent)).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出用户失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/user/student/tpPStudent/list?repage=&isMaster="+tpPStudent.getIsMaster();
	}
}